from decimal import Decimal
from datetime import datetime
from ..repositories import bill_repositories

async def get_bills(user_id, bill_type, type, payment_status, payment_method, current_page, page_size):
    """
    获取账单数据
    :param user_id: 用户ID
    :param bill_type: 账单类型
    :param type: 支付类型
    :param payment_status: 支付状态
    :param payment_method: 支付方式
    :param current_page: 当前页码
    :param page_size: 每页条数
    :return: 账单数据
    """
    bills = await bill_repositories.get_bills(user_id, bill_type, type, payment_status, payment_method)
    
    # 实现分页
    start_index = (current_page - 1) * page_size
    end_index = start_index + page_size
    paginated_bills = bills[start_index:end_index]  # 获取当前页的账单

    # 格式化数据
    formatted_bills = []
    for bill in paginated_bills:
        formatted_bill = {}
        for key, value in bill.items():
            if isinstance(value, Decimal):
                formatted_bill[key] = float(value)
            elif isinstance(value, datetime):
                formatted_bill[key] = value.strftime('%Y/%m/%d-%H:%M:%S')
            elif value is None:
                formatted_bill[key] = ''
            else:
                formatted_bill[key] = value
        # 将bill_id改为id 
        formatted_bill['bill_id'] = formatted_bill['id']
        # 删除多余字段  
        del formatted_bill['id']
        del formatted_bill['user_id']
        # 记录日期保留年月日
        formatted_bill['due_date'] = formatted_bill['due_date'][:10]
        formatted_bills.append(formatted_bill)
        

    return {"code": 0, "total": len(bills), "data": formatted_bills}

async def validate_bill_data(bill_type, amount, type):
    """
    验证账单数据
    :param bill_type: 账单类型
    :param amount: 金额
    :param type: 支付类型
    :return: (bool, str) - (验证是否通过, 错误信息)
    """
    if not bill_type or not bill_type.strip():
        return False, "请输入账单类型"
    if amount <= 0:
        return False, "金额必须大于0"
    if type not in [0, 1]:
        return False, "必须选择支付类型"

    return True, ""

async def add_bill(user_id, bill_type, amount, type, payment_status, payment_method, due_date, description):
    """
    添加账单
    :param user_id: 用户ID
    :param bill_type: 账单类型
    :param amount: 金额
    :param type: 支付类型
    :param payment_status: 支付状态
    :param payment_method: 支付方式
    :param due_date: 记录日期
    :param description: 备注
    :return: 添加账单结果
    """
    # 首先验证输入数据
    is_valid, error_message = await validate_bill_data(bill_type, amount, type)
    if not is_valid:
        return {"code": 1000, "message": error_message}

    if type == 1:
        payment_status = None
    if not due_date:
        due_date = None
        
    try:
        result = await bill_repositories.add_bill(user_id, bill_type, amount, type, payment_status, payment_method, due_date, description)
        
        if result:
            return {"code": 0, "message": "添加账单成功"}
        return {"code": 1, "message": "添加账单失败"}
        
    except Exception as e:
        print(f"添加账单失败: {str(e)}")
        return {"code": 1, "message": f"添加账单失败: {str(e)}"}

async def delete_bill(user_id, bill_id):
    """
    删除账单
    :param user_id: 用户ID
    :param bill_id: 账单ID
    :return: 删除账单结果
    """
    try:
        result = await bill_repositories.delete_bill(user_id, bill_id)
        if result:
            return {"code": 0, "message": "删除账单成功"}
        return {"code": 1, "message": "删除账单失败"}
    except Exception as e:
        print(f"删除账单失败: {str(e)}")
        return {"code": 1, "message": f"删除账单失败: {str(e)}"}

async def update_bill(user_id, bill_id, bill_type, amount, type, payment_status, payment_method, due_date, description):
    """
    更新账单
    :param user_id: 用户ID
    :param bill_id: 账单id
    :param bill_type: 账单类型
    :param amount: 用户金额
    :param type: 支付类型
    :param payment_status: 支付状态
    :param payment_method: 支付方式
    :param due_date: 记录日期
    :param description: 备注
    :return: 更新账单结果
    """
    # 首先验证输入数据
    is_valid, error_message = await validate_bill_data(bill_type, amount, type)
    if not is_valid:
        return {"code": 1000, "message": error_message}

    if type == 1:
        payment_status = None
    if not due_date:
        due_date = None
        
    try:
        result = await bill_repositories.update_bill(user_id, bill_id, bill_type, amount, type, payment_status, payment_method, due_date, description)
        
        if result:
            return {"code": 0, "message": "更新账单成功"}
        return {"code": 1, "message": "更新账单失败"}
        
    except Exception as e:
        print(f"更新账单失败: {str(e)}")
        return {"code": 1, "message": f"更新账单失败: {str(e)}"}
